package com.example.login.controller;

import com.example.login.util.JwtTokenUtil;
import com.example.login.dto.*;
import com.example.login.model.User;
import com.example.login.service.SmsService;
import com.example.login.service.UserService;
import com.example.login.util.ApiResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private SmsService smsService;
    
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    /**
     * 1. 用户登录入口 - 判断是新用户还是老用户
     */
    @PostMapping("/login-check")
    public ResponseEntity<ApiResponse<Map<String, Object>>> loginCheck(@RequestBody Map<String, String> params) {
        String identifier = params.get("identifier");
        String type = params.get("type"); // username 或 phone
        
        if (identifier == null || type == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error("参数不完整"));
        }
        
        boolean exists = userService.checkUserExists(identifier, type);
        
        Map<String, Object> data = new HashMap<>();
        data.put("exists", exists);
        data.put("next", exists ? "login" : "register");
        
        return ResponseEntity.ok(ApiResponse.success(data));
    }
    
    /**
     * 2. 账号密码登录
     */
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<LoginResponse>> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            String token = userService.loginByPassword(loginRequest.getUsername(), loginRequest.getPassword());
            
            LoginResponse loginResponse = new LoginResponse();
            loginResponse.setToken(token);
            loginResponse.setTokenHead(tokenHead);
            
            return ResponseEntity.ok(ApiResponse.success(loginResponse));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.error(401, "用户名或密码错误"));
        }
    }
    
    /**
     * 3. 短信验证码登录
     */
    @PostMapping("/login/sms")
    public ResponseEntity<ApiResponse<LoginResponse>> loginBySms(@Valid @RequestBody SmsLoginRequest request) {
        try {
            LoginResponse loginResponse = userService.loginBySms(request);
            
            // 如果需要注册，返回需要注册的标志
            if (loginResponse.getNeedRegister() != null && loginResponse.getNeedRegister()) {
                return ResponseEntity.ok(ApiResponse.success(loginResponse));
            }
            
            // 正常登录情况
            return ResponseEntity.ok(ApiResponse.success(loginResponse));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.error(401, e.getMessage()));
        }
    }
    
    /**
     * 4. 发送短信验证码
     */
    @PostMapping("/sms/send")
    public ResponseEntity<ApiResponse<Void>> sendSmsCode(@Valid @RequestBody SmsCodeRequest request) {
        boolean sent = smsService.sendVerificationCode(request.getPhone());
        
        if (sent) {
            return ResponseEntity.ok(ApiResponse.success("验证码发送成功", null));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("发送验证码失败"));
        }
    }
    
    /**
     * 5. 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<ApiResponse<Void>> register(@Valid @RequestBody RegisterRequest registerRequest) {
        // 检查用户名是否已存在
        if (userService.checkUserExists(registerRequest.getUsername(), "username")) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("用户名已存在"));
        }
        
        // 检查手机号是否已存在
        if (userService.checkUserExists(registerRequest.getPhone(), "phone")) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("手机号已被注册"));
        }
        
        // 注册新用户
        userService.register(registerRequest);
        
        return ResponseEntity.ok(ApiResponse.success("注册成功", null));
    }

    @PostMapping("/login-by-code")
    public ResponseEntity<?> loginByCode(@Valid @RequestBody SmsLoginRequest request) {
        try {
            // 验证短信验证码
            boolean isValid = userService.verifySmsCode(request.getPhone(), request.getCode());
            if (!isValid) {
                return ResponseEntity.badRequest().body(new ApiResponse<>(400, "验证码错误或已过期", null));
            }

            // 检查用户是否存在
            User user = userService.getUserByPhone(request.getPhone());
            if (user == null) {
                // 用户不存在，返回需要注册的标识
                Map<String, Object> response = new HashMap<>();
                response.put("needRegister", true);
                response.put("phone", request.getPhone());
                return ResponseEntity.ok(new ApiResponse<>(200, "请完成注册", response));
            }

            // 获取UserDetails并生成token
            String token = userService.loginByCode(request.getPhone(), request.getCode());
            
            Map<String, Object> response = new HashMap<>();
            response.put("token", token);
            response.put("user", user);
            response.put("needRegister", false);
            response.put("tokenHead", tokenHead);
            return ResponseEntity.ok(new ApiResponse<>(200, "登录成功", response));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new ApiResponse<>(400, e.getMessage(), null));
        }
    }
} 